package drds.configuration.db.xml_mapping.dynamic_tag.ognl;


import lombok.extern.slf4j.Slf4j;
import ognl.DefaultClassResolver;
import ognl.OgnlException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//import ognl.Ognl;
@Slf4j
public final class Ognl {

    private static MemberAccessImpl memberAccess = new MemberAccessImpl();
    private static DefaultClassResolver defaultClassResolver = new DefaultClassResolver();
    private static Map<String, Object> expressionToExpressionNodeMap = new ConcurrentHashMap<>();

    private Ognl() {
    }

    public static Object getValue(Object root, String expression) {

        try {
            Map defaultContext = ognl.Ognl.createDefaultContext(root, memberAccess, defaultClassResolver, null);
            return ognl.Ognl.getValue(parseExpression(expression), defaultContext, root);
        } catch (OgnlException | NullPointerException e) {
            String errorMessage = "ognl表达式解析错误:" + expression + ",Cause by" + e.getMessage();
            log.error(errorMessage);
            throw new RuntimeException(errorMessage, e);
        }
    }

    private static Object parseExpression(String expression) throws OgnlException {
        Object object = expressionToExpressionNodeMap.get(expression);
        if (object == null) {
            object = ognl.Ognl.parseExpression(expression);
            expressionToExpressionNodeMap.put(expression, object);
        }
        return object;
    }

}
